from flask import Blueprint, render_template, request, jsonify
import random
import string
import math

life_tools_bp = Blueprint('life_tools', __name__)


@life_tools_bp.route('/')
def index():
    tools = [
        {
            'name': '随机数生成',
            'slug': 'random-generator',
            'description': '生成随机数字、字母、字符串等',
            'icon': 'fa-random'
        },
        {
            'name': '密码生成器',
            'slug': 'password-generator',
            'description': '生成安全、强壮的随机密码',
            'icon': 'fa-key'
        },
        {
            'name': 'BMI计算器',
            'slug': 'bmi-calculator',
            'description': '根据身高体重计算身体质量指数',
            'icon': 'fa-weight'
        },
        {
            'name': '抽奖工具',
            'slug': 'lottery-tool',
            'description': '随机抽取名单、生成中奖结果',
            'icon': 'fa-gift'
        }
    ]
    return render_template('tools/life/index.html', tools=tools)


@life_tools_bp.route('/random-generator', methods=['GET', 'POST'])
def random_generator():
    result = None
    params = {}
    
    if request.method == 'POST':
        gen_type = request.form.get('type', 'number')
        
        if gen_type == 'number':
            min_val = int(request.form.get('min', 1))
            max_val = int(request.form.get('max', 100))
            count = int(request.form.get('count', 1))
            
            params = {'type': gen_type, 'min': min_val, 'max': max_val, 'count': count}
            result = [random.randint(min_val, max_val) for _ in range(count)]
            
        elif gen_type == 'letter':
            case = request.form.get('case', 'mixed')
            count = int(request.form.get('count', 10))
            
            params = {'type': gen_type, 'case': case, 'count': count}
            if case == 'upper':
                chars = string.ascii_uppercase
            elif case == 'lower':
                chars = string.ascii_lowercase
            else:
                chars = string.ascii_letters
                
            result = ''.join(random.choice(chars) for _ in range(count))
            
        elif gen_type == 'string':
            length = int(request.form.get('length', 10))
            include_upper = 'include_upper' in request.form
            include_lower = 'include_lower' in request.form
            include_digits = 'include_digits' in request.form
            include_special = 'include_special' in request.form
            
            params = {
                'type': gen_type, 
                'length': length,
                'include_upper': include_upper,
                'include_lower': include_lower,
                'include_digits': include_digits,
                'include_special': include_special
            }
            
            chars = ''
            if include_upper:
                chars += string.ascii_uppercase
            if include_lower:
                chars += string.ascii_lowercase
            if include_digits:
                chars += string.digits
            if include_special:
                chars += string.punctuation
                
            if not chars:
                chars = string.ascii_letters + string.digits
                
            result = ''.join(random.choice(chars) for _ in range(length))
    
    return render_template('tools/life/random_generator.html', result=result, params=params)


@life_tools_bp.route('/password-generator', methods=['GET', 'POST'])
def password_generator():
    result = None
    params = {}
    
    if request.method == 'POST':
        length = int(request.form.get('length', 12))
        include_upper = 'include_upper' in request.form
        include_lower = 'include_lower' in request.form
        include_digits = 'include_digits' in request.form
        include_special = 'include_special' in request.form
        
        params = {
            'length': length,
            'include_upper': include_upper,
            'include_lower': include_lower,
            'include_digits': include_digits,
            'include_special': include_special
        }
        
        chars = ''
        if include_upper:
            chars += string.ascii_uppercase
        if include_lower:
            chars += string.ascii_lowercase
        if include_digits:
            chars += string.digits
        if include_special:
            chars += string.punctuation
            
        if not chars:
            chars = string.ascii_letters + string.digits
            
        result = ''.join(random.choice(chars) for _ in range(length))
    
    return render_template('tools/life/password_generator.html', result=result, params=params)


@life_tools_bp.route('/bmi-calculator', methods=['GET', 'POST'])
def bmi_calculator():
    result = None
    category = None
    params = {}
    
    if request.method == 'POST':
        height = float(request.form.get('height', 170)) / 100  # 转换为米
        weight = float(request.form.get('weight', 60))
        unit = request.form.get('unit', 'metric')
        
        params = {'height': height * 100, 'weight': weight, 'unit': unit}
        
        if unit == 'imperial':
            # 英制单位下，身高为英尺，体重为磅
            height = height * 0.3048  # 转换为米
            weight = weight * 0.453592  # 转换为公斤
        
        # 计算BMI
        bmi = weight / (height * height)
        result = round(bmi, 2)
        
        # 确定BMI分类
        if bmi < 18.5:
            category = '体重过轻'
        elif 18.5 <= bmi < 24:
            category = '正常范围'
        elif 24 <= bmi < 28:
            category = '超重'
        elif 28 <= bmi < 32:
            category = '肥胖'
        else:
            category = '重度肥胖'
    
    return render_template('tools/life/bmi_calculator.html', 
                          result=result, 
                          category=category, 
                          params=params)


@life_tools_bp.route('/lottery-tool', methods=['GET', 'POST'])
def lottery_tool():
    result = None
    params = {}
    
    if request.method == 'POST':
        names = request.form.get('names', '').strip().split('\n')
        names = [name.strip() for name in names if name.strip()]
        count = int(request.form.get('count', 1))
        
        params = {'names': '\n'.join(names), 'count': count}
        
        if names:
            if count >= len(names):
                result = names
                random.shuffle(result)
            else:
                result = random.sample(names, count)
    
    return render_template('tools/life/lottery_tool.html', result=result, params=params) 